<?php

namespace App\Http\Middleware;

use App\Model\Admin;
use App\Model\ApiToken;
use App\Tool\Doctrine;
use App\Tool\Json;
use Closure;
use Nette\Reflection\ClassType;

class CheckLogin
{

    /**
     * Create by Peter
     * 2019/08/27 17:13:12
     * Email:904801074@qq.com
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Http\JsonResponse|mixed
     * @throws \ReflectionException
     */
    public function handle($request, Closure $next)
    {



        $route=$request->route();

        $controller=$route->action['controller'];

        $c=explode('@',$controller);

        $class=new ClassType($c[0]);

        $prototype=$class->getMethod($c[1])->getAnnotation('Auth')['type'];



        if($prototype=='no_check') return $next($request);



        $token = $request->header('token') ?? null;

        if (!$token) return response()->json(Json::codeArray(11, 'token为空！'));

        $re = ApiToken::where('token', $token)->first();

        if (!$re) return response()->json(Json::codeArray(10, 'token验证失败！'));

        $expire_time = $re->expire_time;


        if ($expire_time < time()) {

            //删除已过期的token
            ApiToken::destroy($re->id);

            return response()->json(Json::codeArray(12, 'token已过期'));
        }


        $admin_id = $re->admins_id;

        $info = Admin::where('id', $admin_id)->first();

        if(!$info) return response()->json(Json::codeArray(13, 'token对应的管理员不存在'));

        app()->instance('adminInfo', $info->toArray());

        $rand=mt_rand(1,3);

        //过期时间向后移三天(随机概率)
        if($rand==3) $re->increment('expire_time',60*60*24*3);

        return $next($request);
    }
}
